package com.shengruan.index.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.shengruan.admin.vo.Question;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shengruan.admin.jdbc.ContentJdbc;
import com.shengruan.admin.jdbc.UserJdbc;
import com.shengruan.admin.util.MessageUtil;
import com.shengruan.admin.vo.User;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
import com.shengruan.common.Function;
import com.shengruan.framework.util.AuthFactory;
import com.shengruan.index.dto.RegistrationDTO;
import com.shengruan.servlet.ServletUtils;
import com.shengruan.admin.jdbc.QuestionJdbc;
import com.shengruan.user.jdbc.SMSRecordJdbc;
import com.shengruan.user.vo.SMSRecord;

public class RegistrationAction extends BaseAction {

    Logger logger = LoggerFactory.getLogger(getClass());

    private UserJdbc userJdbc = (UserJdbc) this.getJdbc(UserJdbc.class);
    private QuestionJdbc questionJdbc = (QuestionJdbc) this.getJdbc(QuestionJdbc.class);
    private SMSRecordJdbc smsRecordJdbc = (SMSRecordJdbc) this.getJdbc(SMSRecordJdbc.class);
    private ContentJdbc contentJdbc = (ContentJdbc) this.getJdbc(ContentJdbc.class);
    /**
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    public void init() throws Exception {
        this.saveToken();
        this.setRequest("content", contentJdbc.getById(5).getContent());
        this.forward("/BasicInformation.jsp");
    }

    /**
     * 初始化注册页面的参数
     *
     * @param request
     * @param userName
     * @param password
     * @param realName
     * @param mobile
     * @param email
     */
    private void setParameterAttribute(HttpServletRequest request, String userName, String password, String realName, String mobile, String email, String questionAnswer, String questionAnswer2) {
        this.setRequest("userName", StringUtils.trim(userName));
        this.setRequest("password", StringUtils.trim(password));
        this.setRequest("realName", StringUtils.trim(realName));
        this.setRequest("mobile", StringUtils.trim(mobile));
        this.setRequest("email", StringUtils.trim(email));
        this.setRequest("questionAnswer", StringUtils.trim(questionAnswer));
        this.setRequest("questionAnswer2", StringUtils.trim(questionAnswer2));
        List<Question> questionList = questionJdbc.loadAll();
        this.setRequest("questionList", questionList);
    }


    private void setParameterAttribute(String mobile, String invitePeople, String email, String userName) {
        this.setRequest("mobile", StringUtils.trim(mobile));
        this.setRequest("invitePeople", StringUtils.trim(invitePeople));
        this.setRequest("userName", StringUtils.trim(userName));
        this.setRequest("email", StringUtils.trim(email));
        this.saveToken();
        this.setRequest("content", contentJdbc.getById(5).getContent());
    }

    /**
     * 基本信息注册提交
     *
     * @throws Exception
     */
    public void basicInformation() throws Exception {
        String userName = this.input("userName");
        String password = this.input("password");
        String password_confirm = this.input("password_confirm");
        String mobile = this.input("mobile");
        String email = this.input("email");
        String code = this.input("code");
        String invitePeople = this.input("invitePeople");


        //表单重复提交
        if (this.isTokenValid()) {
            this.setRequest("content", contentJdbc.getById(5).getContent());
            this.forward("/BasicInformation.jsp");
            return;
        }


        if (StringUtils.isEmpty(userName)) {
            setParameterAttribute(mobile, invitePeople, email, userName);
            this.setRequest(Constants.MESSAGE, "请输入会员名");
            this.forward("/BasicInformation.jsp");
            return;
        }
        if (StringUtils.isEmpty(password)) {
            setParameterAttribute(mobile, invitePeople, email, userName);
            this.setRequest(Constants.MESSAGE, "请输入会员密码");
            this.forward("/BasicInformation.jsp");
            return;
        }
        if (StringUtils.isEmpty(password_confirm)) {
            setParameterAttribute(mobile, invitePeople, email, userName);
            this.setRequest(Constants.MESSAGE, "请输入确认密码");
            this.forward("/BasicInformation.jsp");
            return;
        }

        if (!password.equals(password_confirm)) {
            setParameterAttribute(mobile, invitePeople, email, userName);
            this.setRequest(Constants.MESSAGE, "两次输入的密码必须相同");
            this.forward("/BasicInformation.jsp");
            return;
        }


        /*if (StringUtils.isEmpty(mobile)) {
            setParameterAttribute(mobile, invitePeople, email, userName);
            this.setRequest(Constants.MESSAGE, "请输入手机号码");
            this.forward("/BasicInformation.jsp");
            return;
        }*/

        if (StringUtils.isEmpty(email)) {
            setParameterAttribute(mobile, invitePeople, email, userName);
            this.setRequest(Constants.MESSAGE, "请输入电子邮件.");
            this.forward("/BasicInformation.jsp");
            return;
        }


        if (StringUtils.isEmpty(code)) {
            setParameterAttribute(mobile, invitePeople, email, userName);
            this.setRequest(Constants.MESSAGE, "请输入验证码.");
            this.forward("/BasicInformation.jsp");
            return;
        }

        String validateCode = (String) ServletUtils.getSessionAttribute(request, "validateCode");
        if (StringUtils.isEmpty(validateCode) || !code.equalsIgnoreCase(validateCode)) {
            setParameterAttribute(mobile, invitePeople, email, userName);
            this.setRequest(Constants.MESSAGE, "验证码不正确.");
            this.forward("/BasicInformation.jsp");
            return;
        }


        RegistrationDTO registrationDTO = new RegistrationDTO();
        registrationDTO.setUserName(StringUtils.trim(userName));
        registrationDTO.setPassword(StringUtils.trim(password));
        //registrationDTO.setMobile(StringUtils.trim(mobile));
        registrationDTO.setInvitePeople(StringUtils.trim(invitePeople));
        registrationDTO.setEmail(StringUtils.trim(email));
        this.setSession("registrationDTO", registrationDTO);

        List<Question> questionList = questionJdbc.loadAll();
        this.setRequest("questionList", questionList);


        this.forward("/InformationCheck.jsp");
    }

    /**
     * 信息校验
     *
     * @throws Exception
     */
    public void informationCheck() throws Exception {
        String questionId = this.input("questionId1");
        String questionId2 = this.input("questionId2");
        String questionAnswer = this.input("questionAnswer");
        String questionAnswer2 = this.input("questionAnswer2");



        RegistrationDTO registrationDTO = (RegistrationDTO) request.getSession().getAttribute("registrationDTO");
        if("-1".equals(questionId)) {
            String questionCustomize1 = this.input("questionCustomize1");
            registrationDTO.setQuestionCustomize1(StringUtils.trim(questionCustomize1));
        }

        if("-1".equals(questionId2)) {
            String questionCustomize2 = this.input("questionCustomize2");
            registrationDTO.setQuestionCustomize2(StringUtils.trim(questionCustomize2));
        }

        registrationDTO.setQuestionId(questionId);
        registrationDTO.setQuestionId2(questionId2);
        registrationDTO.setQuestionAnswer(questionAnswer);
        registrationDTO.setQuestionAnswer2(questionAnswer2);

        User user = new User();
        user.setUserName(registrationDTO.getUserName());
        AuthFactory.passwordKey = Constants.passwordKey;
        user.setPassword(AuthFactory.encryptPassword(registrationDTO.getPassword()));
        user.setMobile(registrationDTO.getMobile());
        user.setEmail(registrationDTO.getEmail());
        user.setCreationTime(System.currentTimeMillis());
        user.setLoginAttempts(1);
        user.setLoginTime(0l);
        user.setLogins(0);//初始化登录次数为0


        userJdbc.registration(user, registrationDTO);

        user.setPassword(registrationDTO.getPassword());
        this.setSession(Constants.USER, user);

        this.setRequest(Constants.MESSAGE, "注册成功");


        this.redirect("/login.ac");
    }

    /**
     * 手机号码校验
     *
     * @throws ServletException
     * @throws IOException
     */
    public void mobileCheck() throws Exception {
        RegistrationDTO registrationDTO = (RegistrationDTO) request.getSession().getAttribute("registrationDTO");
        String telephone = registrationDTO.getMobile();
        String code = input("mobileCode");
        if (code == null || "".equals(code) || code.length() != 6 || telephone == null || "".equals(telephone) || telephone.length() != 11) {
            //参数非法
            this.print("errorCode");
        }
      
        SMSRecord smsRecord = smsRecordJdbc.getByTelephone(telephone);
        if (smsRecord == null) {
            //验证记录不存在
            this.print("errorCode");
        } else {
            if (code.equals(smsRecord.getCode())) {
                long nowTime = System.currentTimeMillis();
                long sendTime = smsRecord.getTime();
                if (nowTime - sendTime > 1000 * 60 * 5) {
                    //超时
                    this.print("timeout");
                    return;
                }
                if (smsRecord.getState() == 1) {
                    //已经校验过
                    this.print("used");
                    return;
                }
                smsRecordJdbc.updateState(smsRecord.getId());
                //校验成功
                //this.print("success");
            } else {
                //检验吗错误
                this.print("errorCode");
            }

        }
   
    
        User user = new User();
        user.setUserName(registrationDTO.getUserName());
        AuthFactory.passwordKey = Constants.passwordKey;
        user.setPassword(AuthFactory.encryptPassword(registrationDTO.getPassword()));
        user.setMobile(registrationDTO.getMobile());
        user.setEmail(registrationDTO.getEmail());
        user.setCreationTime(System.currentTimeMillis());
        user.setLoginAttempts(1);
        user.setLoginTime(0l);
        user.setLogins(1);//初始化登录次数为1

        /*List<Question> questionList = new ArrayList<Question>();
        questionList.add(new Question(Integer.valueOf(registrationDTO.getQuestionId()), registrationDTO.getQuestionAnswer()));
        questionList.add(new Question(Integer.valueOf(registrationDTO.getQuestionId2()), registrationDTO.getQuestionAnswer2()));*/

        userJdbc.registration(user, registrationDTO);

        user.setPassword(registrationDTO.getPassword());
        this.setSession(Constants.USER, user);

        this.setRequest(Constants.MESSAGE, "注册成功");

        //this.forward("/RegistrationSuccess.jsp");
        this.redirect("/login.ac");
    }


    /**
     * check by mobile
     *
     * @throws Exception
     */
    public void checkMobile() throws Exception {
        String mobile = this.input("mobile");
        User user = userJdbc.getByMobile(mobile);
        if (null == user) {
            this.print("true");
        } else {
            this.print("false");
        }
    }

    /**
     * @throws Exception
     */
    public void checkUserName() throws Exception {
        String UserName = this.input("userName");
        User user = userJdbc.getByUserName(UserName);
        if (null == user) {
            this.print("true");
        } else {
            this.print("false");
        }
    }


    /**
     * @throws Exception
     */
    public void checkEmail() throws Exception {
        String email = this.input("email");
        User user = userJdbc.getByEmail(email);
        if (null == user) {
            this.print("true");
        } else {
            this.print("false");
        }
    }

    /**
     * 生成校验码
     *
     * @throws Exception
     */
    public void CheckCodeGeneration() throws Exception {
        this.print("true");
    }

    /**
     * 发送手机短信
     *
     * @throws Exception
     */
    public void sendSMS() throws Exception {
        RegistrationDTO registrationDTO = (RegistrationDTO) request.getSession().getAttribute("registrationDTO");
        String telephone = registrationDTO.getMobile();
        if (telephone == null || "".equals(telephone) || telephone.length() != 11) {
            this.print("false");
        } else {
        	
        	SMSRecord oldSmsRecord = smsRecordJdbc.getByTelephone(telephone);
        	if(oldSmsRecord!=null)
        	{
        		long sendTime = oldSmsRecord.getTime();
        		if(System.currentTimeMillis()-sendTime<1000*30)
        		{
        			this.print("faster");
        			return;
        		}
        	}
            String code = "" + Math.round(Math.random() * 899999 + 100000);
            SMSRecord smsRecord = new SMSRecord();
            smsRecord.setCode(code);
            smsRecord.setIp(Function.getIpAddr(request));
            smsRecord.setState(0);
            smsRecord.setTime(System.currentTimeMillis());
            smsRecord.setTelephone(telephone);
            SMSRecordJdbc smsRecordJdbc = new SMSRecordJdbc();
            smsRecordJdbc.save(smsRecord);
            this.print(code);
            
            /***调用接口发送短信***/
            MessageUtil.sendSMS(telephone, code);
        }

    }

    /**
     * 检查手机验证码是否合法
     */
    public void checkSMSCode() throws Exception {
        RegistrationDTO registrationDTO = (RegistrationDTO) request.getSession().getAttribute("registrationDTO");
        String telephone = registrationDTO.getMobile();
        String code = input("code");
        if (code == null || "".equals(code) || code.length() != 6 || telephone == null || "".equals(telephone) || telephone.length() != 11) {
            //参数非法
            this.print("errorCode");
            return;
        }
      
        SMSRecord smsRecord = smsRecordJdbc.getByTelephone(telephone);
        if (smsRecord == null) {
            //验证记录不存在
            this.print("errorCode");
        } else {
            if (code.equals(smsRecord.getCode())) {
                long nowTime = System.currentTimeMillis();
                long sendTime = smsRecord.getTime();
                if (nowTime - sendTime > 1000 * 60 * 5) {
                    //超时
                    this.print("timeout");
                    return;
                }
                if (smsRecord.getState() == 1) {
                    //已经校验过
                    this.print("used");
                    return;
                }
                
                this.print("success");
            } else {
                //检验吗错误
                this.print("errorCode");
                return;
            }

        }
    }
}
